<?php


class Admin_AuthController extends Zend_Controller_Action {

    public function init(){
        
    }
    public function loginAction(){        
        $request = $this->getRequest();
        $form = new Admin_Form_Login();
        $db = Zend_Db_Table::getDefaultAdapter();
        $flash = $this->_helper->getHelper('FlashMessenger');
        if($request->isPost()){
            $formData = $request->getPost();            
            if($form->isValid($formData)){                
                $adapter = new Zend_Auth_Adapter_DbTable($db,'admin','username','password','MD5(?)');
                $adapter->setIdentity($form->getValue('username'));
                $adapter->setCredential($form->getValue('password'));
                $auth = Zend_Auth::getInstance();
                $auth->setStorage(new Zend_Auth_Storage_Session(SESSION_NAMESPACE));
                $result = $auth->authenticate($adapter);                
                if ($result->isValid())
                {                                        
                    $adminModel = new Default_Model_Admin();
                    $userInfo = $adminModel->getDataByUsername($form->getValue('username'));
                    if($userInfo['status'] == 1){
                        $auth->getStorage()->write(array(
                        'username' => $userInfo->username,
                        'adminId' => $userInfo->id,
                        'role'=>$userInfo->role));
                        $session = new Zend_Session_Namespace(SESSION_NAMESPACE);
                        $session->setExpirationSeconds(60*60*24);
                                                             
                        $redirectUrl        = $this->getRequest()->getParam('redirectUrl', '');
                        if($redirectUrl != ''){
                            $this->_redirect($redirectUrl);
                        }else{
                            $this->_helper->redirector('index','index','admin');
                        }                        
                    }else{                          
                        
                    }                    
                }
            }
        }        
        //$this->view->messages = $flash->getMessage();
        $this->view->loginForm = $form;
    }
    public function logoutAction(){
        $this->_helper->layout()->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);
        $a = My_Auth::logout('Zend_Auth_KPI_ASMEMBER');
        if($a){
            $this->_helper->redirector('index', 'user', 'admin');
            exit;
        }
        My_Auth::logout();
        $this->_helper->redirector('login', 'auth', 'admin');
        exit;
    }

} 